import React from 'react';
import { useRef } from 'react'
import HOST from '../../utils/const';
import useTitle from '../../hooks/useTitle';
import { useHistory } from "react-router-dom";
import axios from 'axios';
import './index.css';

function Login() {
  useTitle(Login.title);

  const password = useRef(null);
  const username = useRef(null);

  const history = useHistory()

  function gotoRegister(){
    history.push('/register')
    history.go(0)
  }

  function gotoIndex(){
    history.push('/index')
    history.go(0)
  }
  function login(){
    const psw = password.current.value;
    const usn = username.current.value;
    axios.get(HOST+`/method/login?username=${usn}&password=${psw}`).then((res)=>{
      switch (res.data) {
        case 'code=-1\n': {
          alert('密码错误或用户名不存在')
          break;
        }
        case 'code=0\n' :{
          alert('登陆成功');
          localStorage.setItem('username', usn);
          gotoIndex();
          break;
        }
        default: {
          alert('未知错误');
          break;
        }
      }
    }).catch((err)=>{
      console.log(err);
    })
  }
  return (
    <div className='login'>
      <div className='loginimg'></div>
      <div className='inputframe'>
        <div>
        <div className='login-topbar'>
          <div className='topbar-sign'>登陆</div>
          <div className='register' onClick={gotoRegister}>
            还没账号，去注册
          </div>
     
        </div>
        <div className='devide-line'></div>
        </div>
        <div className='two-input'>
        <div className='username'>
        <div className='sign'>账号:</div>
          <input type="text" id='username' ref={username} className='input-f'  placeholder='请输入账号'/>
        </div>
        <div className='password'>
          <div className='sign'>密码:</div>
          <input type="password" id='password' ref={password} className='input-f' placeholder='请输入密码'/>
        </div>
        </div>
        <div className='button-box'>
        <button className='login-button' onClick={login}>
          登陆
        </button>
        </div>
      </div>
    </div>
  );
}

Login.path = '/login';
Login.title = '登陆';
Login.meta = {
    keywords:
      '登陆',
    description:
      '宠物医院 角色扮演 学习知识 登陆界面'
  };
Login.exact = true;

export default Login;
